#include "AnalogButton.h"

extern "C" {
#include <avr/interrupt.h>
#include <avr/io.h>
}

AnalogButtonClass AnalogButton;

void AnalogButtonClass::begin(byte adc, byte buttons, int *values, AnalogButtonPushed *analogButtonPushed) {
	this->adc = adc;
	this->buttons = buttons;
	this->values = values;
	this->analogButtonPushed = analogButtonPushed;
	
	this->lastButton = 255;
	this->lastButtonPushed = 255;

	ADMUX = (1 << REFS0); // Set ADC reference to AVCC
	ADMUX |= 0x0f & adc; // Set ADC channel
	ADCSRA |= (1 << ADATE);  // Set ADC to Free-Running Mode
	ADCSRA |= (1 << ADIE);  // Enable ADC Interrupt
	ADCSRA |= (1 << ADSC);  // Start A2D Conversions
}

void AnalogButtonClass::handleValue(int value) {
	byte i;

    for(i=0; i<buttons; i++) {
	    if(value < AnalogButton.values[i]) {
		  break;
	    }
	}
	
	if(i < buttons) {
		unsigned long current = millis();
		if(i == lastButton) {
			if(current - lastMillis > 50 && i != lastButtonPushed) {
				AnalogButton.analogButtonPushed(i);
				lastButtonPushed = i;
			}
		} else {
			lastMillis = current;
			lastButtonPushed = 255;
		}
	}		

	lastButton = i;
}

ISR(ADC_vect)
{
  uint8_t low, high;
  low = ADCL;
  high = ADCH;
  int value = (high << 8) | low;
  
  AnalogButton.handleValue(value);
} 
